package homework.Arrays;

public class ArraySearch {


    public static int findFirstOccurrence(int[] array, int target) {
        for (int i = 0; i < array.length; i++) {
            if (array[i] == target) {
                return i; // 找到目标值，返回当前索引
            }
        }
        return -1; // 遍历完数组未找到目标值
    }

    public static void main(String[] args) {
        // 测试用例1: 目标值存在于数组中
        int[] testArray1 = {1, 2, 3, 4, 5, 6, 7};
        int target1 = 5;
        int result1 = findFirstOccurrence(testArray1, target1);
        System.out.println("测试1 - 数组: " + java.util.Arrays.toString(testArray1));
        System.out.println("目标值 " + target1 + " 第一次出现的索引: " + result1);
        System.out.println("预期结果: 4");
        System.out.println();

        // 测试用例2: 目标值不存在于数组中
        int[] testArray2 = {2, 4, 6, 8, 10};
        int target2 = 5;
        int result2 = findFirstOccurrence(testArray2, target2);
        System.out.println("测试2 - 数组: " + java.util.Arrays.toString(testArray2));
        System.out.println("目标值 " + target2 + " 第一次出现的索引: " + result2);
        System.out.println("预期结果: -1");
        System.out.println();
    }
}
